/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.monitor.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.common.constant.HistoryTableEnum;
import org.springblade.common.constant.OperatingSystemEnum;
import org.springblade.common.constant.PortInOutEnum;
import org.springblade.common.tool.CommonUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.monitor.dto.ChartDTO;
import org.springblade.modules.monitor.dto.DiskDTO;
import org.springblade.modules.monitor.dto.DiskMetadata;
import org.springblade.modules.monitor.mapper.HostInfoMapper;
import org.springblade.modules.monitor.mapper.NetEquipMapper;
import org.springblade.modules.monitor.mapper.WorkOrderMapper;
import org.springblade.modules.monitor.pojo.*;
import org.springblade.modules.monitor.service.IHostInfoService;
import org.springblade.modules.monitor.service.INetEquipInfoService;
import org.springblade.modules.monitor.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

import static org.springblade.common.tool.CommonUtil.transferHealthyValue;

/**
 *  服务实现类
 *
 * @author Blade
 * @since 2020-05-17
 */
@Service
public class NetEquipServiceImpl extends ServiceImpl<NetEquipMapper, NetEquipInfoVO> implements INetEquipInfoService {
	@Autowired
	private NetEquipMapper netEquipMapper;

	@Autowired
	private HostInfoMapper hostInfoMapper;

	@Autowired
	private WorkOrderMapper workOrderMapper;

	@Override
	public NetEquipInfoVO getDetail(Long interfaceid) {
		NetEquipInfoVO detail = netEquipMapper.getDetail(interfaceid);
		List<Map<String, String>> list = netEquipMapper.getBaseInfo(detail.getHostid());
		list.forEach(x->{
			//厂商
			if("system.name".equals(x.get("key_"))){
				detail.setFactory(x.get("value"));
			}

			//联系方式
			if("system.contact[sysContact.0]".equals(x.get("key_"))){
				detail.setContact(x.get("value"));
			}

			//型号
			if("system.descr[sysDescr.0]".equals(x.get("key_"))){
				detail.setTypeDescr(x.get("value"));
			}
		});

		return detail;
	}

	@Override
	public List<PowerSupply> getPowerSupplyStatus(Long interfaceid) {
		NetEquipInfoVO detail = netEquipMapper.getDetail(interfaceid);
		List<PowerSupply> powerSupplies = new ArrayList<>();
		List<Map<String, Object>> list = netEquipMapper.getPowerSupplyStatus(detail.getHostid());
		list.forEach(x->{
			//TODO 判断当前为何种厂商，可能状态描述存在出入
			PowerSupply powerSupply = new PowerSupply();
			powerSupply.setName(x.get("name").toString());
			String value = String.valueOf(x.get("value"));
			powerSupply.setStatus(value);
			if(value.equals("1")){
				powerSupply.setStatusDes("active");
			}else if(value.equals("2")){
				powerSupply.setStatusDes("deactive");
			}else if(value.equals("3")){
				powerSupply.setStatusDes("not-install");
			}
			powerSupplies.add(powerSupply);
		});
		return powerSupplies;
	}

	@Override
	public StorageCenterVO getStorageCenterDetail(Long interfaceid) {
		//获取 存储基础信息
		NetEquipInfoVO hostInfo = netEquipMapper.getDetail(interfaceid);
		List<Map<String, Object>> strValues = hostInfoMapper.getCommonLatestItemsValue(hostInfo.getHostid(), HistoryTableEnum.history_str.name());
		List<Map<String, Object>> intValues = hostInfoMapper.getCommonLatestItemsValue(hostInfo.getHostid(), HistoryTableEnum.history_uint.name());
		List<Map<String, Object>> values = hostInfoMapper.getCommonLatestItemsValue(hostInfo.getHostid(), HistoryTableEnum.history.name());
		StorageCenterVO temp = CommonUtil.transferStorageCenter(strValues,intValues,values);
		temp.setHost(hostInfo.getHost());
		temp.setIp(hostInfo.getIp());
		temp.setPort(hostInfo.getPort());
		temp.setManageStatus(hostInfo.getStatus());
		temp.setManageType(hostInfo.getType());
		//计算存储设备健康度
		Integer alertCount = workOrderMapper.selectCountByHostname(hostInfo.getHost());
		temp.setHealthyValue(transferHealthyValue(alertCount));
		return temp;
	}

	/**
	 * 获取三层交换机信息
	 *
	 * @param interfaceid
	 * @return
	 */
	@Override
	public ThreeLayerSwitchVO getThreeLayerSwitchDetail(Long interfaceid) {
		NetEquipInfoVO hostInfo = netEquipMapper.getDetail(interfaceid);
		List<Map<String, Object>> strValues = hostInfoMapper.getCommonLatestItemsValue(hostInfo.getHostid(), HistoryTableEnum.history_str.name());
		List<Map<String, Object>> intValues = hostInfoMapper.getCommonLatestItemsValue(hostInfo.getHostid(), HistoryTableEnum.history_uint.name());
		List<Map<String, Object>> values = hostInfoMapper.getCommonLatestItemsValue(hostInfo.getHostid(), HistoryTableEnum.history.name());
		ThreeLayerSwitchVO temp = CommonUtil.transferThreeLayerSwitch(strValues,intValues,values);
		temp.setHost(hostInfo.getHost());
		temp.setIp(hostInfo.getIp());
		temp.setPort(hostInfo.getPort());
		temp.setManageStatus(hostInfo.getStatus());
		temp.setManageType(hostInfo.getType());
		Long startTime = CommonUtil.getSecondFromTime(LocalDateTime.now().minusHours(3));
		Long endTime = CommonUtil.getSecondFromTime(LocalDateTime.now());
		List<ItemSpeedChartResult> inResults = netEquipMapper.getNetEquipTotalSpeed(startTime, endTime, temp.getInSpeedItems());
		List<ItemSpeedChartResult> outResults = netEquipMapper.getNetEquipTotalSpeed(startTime, endTime, temp.getOutSpeedItems());
		temp.setInSpeedTrend(inResults);
		temp.setOutSpeedTrend(outResults);
		return temp;
	}

	@Override
	public SwitchVO getSwitchDetail(Long interfaceid) {
		NetEquipInfoVO hostInfo = netEquipMapper.getDetail(interfaceid);
		List<Map<String, Object>> strValues = hostInfoMapper.getCommonLatestItemsValue(hostInfo.getHostid(), HistoryTableEnum.history_str.name());
		List<Map<String, Object>> intValues = hostInfoMapper.getCommonLatestItemsValue(hostInfo.getHostid(), HistoryTableEnum.history_uint.name());
		List<Map<String, Object>> values = hostInfoMapper.getCommonLatestItemsValue(hostInfo.getHostid(), HistoryTableEnum.history.name());

		List<EquipKind> list = netEquipMapper.getEquipKind();
		String kindType = "";
		for (EquipKind equipKind : list) {
			if(equipKind.getInterfaceid().equals(interfaceid)){
				kindType = equipKind.getEquipKind();
			}
		}
		SwitchVO temp = null;
		if(kindType.equals("26")){
			temp = CommonUtil.transferFirewall(strValues,intValues,values);
		}else{
			temp = CommonUtil.transferSwitch(strValues,intValues,values);
		}

		temp.setHost(hostInfo.getHost());
		temp.setIp(hostInfo.getIp());
		temp.setPort(hostInfo.getPort());
		temp.setManageStatus(hostInfo.getStatus());
		temp.setManageType(hostInfo.getType());
		Long startTime = CommonUtil.getSecondFromTime(LocalDateTime.now().minusHours(3));
		Long endTime = CommonUtil.getSecondFromTime(LocalDateTime.now());
		List<ItemSpeedChartResult> inResults = netEquipMapper.getNetEquipTotalSpeed(startTime, endTime, temp.getInSpeedItems());
		List<ItemSpeedChartResult> outResults = netEquipMapper.getNetEquipTotalSpeed(startTime, endTime, temp.getOutSpeedItems());
		temp.setInSpeedTrend(inResults);
		temp.setOutSpeedTrend(outResults);
		return temp;
	}

	@Override
	public List<ItemChartResult> getPortBytesInfo(ChartDTO chartDTO) {
		//TODO  对时间进行转换
		Long startTime;
		Long endTime;
		if(null!=chartDTO.getStartTime()){
			startTime = CommonUtil.getSecondFromTime(chartDTO.getStartTime());
		}else{
			startTime = CommonUtil.getSecondFromTime(LocalDateTime.now().minusHours(3));
		}

		if(null!=chartDTO.getEndTime()){
			endTime = CommonUtil.getSecondFromTime(chartDTO.getEndTime());
		}else {
			endTime = CommonUtil.getSecondFromTime(LocalDateTime.now());
		}

		List<ItemChartResult> list = netEquipMapper.getBaseItemInfo(chartDTO.getItemid(),startTime,endTime,HistoryTableEnum.history_uint.name());
		list.forEach(x->{
			x.setValue(CommonUtil.fun2(x.getValue()/1024/1024));
			x.setUnit("Mbps");
		});
		return list;
	}


	@Override
	public IPage<NetEquipInfoVO> selectNetEquipPage(IPage<NetEquipInfoVO> page, NetEquipInfoVO netEquipInfoVO) {
		return page.setRecords(baseMapper.selectNetEquipInfoPage(page, netEquipInfoVO));
	}

	@Override
	public List<EquipKindGroup> getEquipKind() {
		List<EquipKind> list = netEquipMapper.getEquipKind();
		//对list进行处理,组装成 EquipKindGroup
		List<EquipKindGroup> equipKindGroupList = new ArrayList<>();
		List<String> collect = list.stream().map(x -> x.getEquipKind()).collect(Collectors.toList());
		LinkedHashSet<String> set = new LinkedHashSet(collect);

		equipKindGroupList = set.stream().map(x -> {
			EquipKindGroup equipKindGroup = new EquipKindGroup();
			List<EquipKind> kinds = new ArrayList<>();
			equipKindGroup.setEquipKind(x);
			for (EquipKind equipKind : list) {
				if (equipKind.getEquipKind().equals(x)) {
					equipKindGroup.setEquipKindName(equipKind.getEquipKindName());
					kinds.add(equipKind);
				}
			}
			equipKindGroup.setEquipKindList(kinds);
			return equipKindGroup;
		}).collect(Collectors.toList());

		return equipKindGroupList;
	}



}
